#include <main.h>
#include <stdio.h>
#include <parser.h>
#include <errcode.h>
#include <stdlib.h>
#include <lexer.h>

extern FILE *tape;
extern FILE *pfOutput;
FILE *pfPipe;
char szCmd[64];

int main(int argc, char* argv[])
{
        int i;
	if (argc < 3){
	  fprintf(stderr, " MyPas usage:\n\t<bin_name> <input_file> <output_file> <object_file>\n");
	  fprintf(stderr, " Example:\n\t ./mypas archive.mypas archive.s output\n");
	  exit(-1);
	}
	if( !(tape = fopen(argv[1], "r")) ){
	  tape = stdin;
	}
	if( !(pfOutput = fopen(argv[2], "w")) ){
	  pfOutput = stdout;
	}
	lookahead = gettoken();
	program();
	if ( giErrFlag != NOERR ){ /* Error Handling */
	  for ( i = 0; i < giNextErrEntry; i++ ){
	    printf(szErrMsg[i]);
	    if ( giErrFlag & FATALERR ) // Fatal error?
	      pfOutput = fopen(argv[2], "w");  // Resetting output
	    
	  }
	}
	/* everything ok, lets compile and link asm code*/
	sprintf(szCmd, "gcc -m32 %s -o %s", argv[2], argv[3]);
	if ( (pfPipe = popen(szCmd, "r")) == NULL ){
	  fprintf(stderr, " MyPas err: Cannot compile and link Assembly code %s", argv[2]);
	  exit(-1);	  
	}
	fclose(pfOutput);
	pclose(pfPipe);
	return 0;
}